import Qust from "/js/Qust.js";
import { $, $$ } from "/js/JSelect.js";
const qust = Qust.create({
	baseUrl: "http://www.rushmc.top/api/",
});
window.currentPage = 1;
window.maxPage = 1;

/* 生命周期-加载完成 */
if (localStorage.getItem("uid") == undefined) {
	$$.navigateTo("/html/login.html");
}
$("#sayhelloh1").setText("欢迎回来，" + localStorage.getItem("uname") + "！");
$("#user-info-name").setText(localStorage.getItem("username"));
$("#user-info-detail").setHtml(`用户id：${localStorage.getItem("uid")}<br>手机：${localStorage.getItem("uphone")}`);
$("#user-info-avatar").setAttr("src", `http://www.rushmc.top/${localStorage.getItem("uavatar")}`);
getNews(1);

/* 事件绑定 */
$("#page-home").click(() => {
	if (window.mode == "get") {
		getNews(1);
	} else {
		searchNews(1);
	}
});
$("#page-backwards").click(() => {
	if (window.currentPage == 1) {
		return false;
	} else {
		if (window.mode == "get") {
			getNews(window.currentPage - 1);
		} else {
			searchNews(window.currentPage - 1);
		}
	}
});
$("#page-forwards").click(() => {
	if (window.currentPage == window.maxPage) {
		return false;
	} else {
		if (window.mode == "get") {
			getNews(window.currentPage + 1);
		} else {
			searchNews(window.currentPage + 1);
		}
	}
});
$("#add-new").click(() => {
	$$.navigateTo("/html/add_new.html");
});
$("#to-usercenter").click(() => {
	$$.navigateTo("/html/user_center.html");
});
$("#search-button").click(() => {
	let search = $("#search").value;
	if (search == "") {
		getNews(1);
		return false;
	}
	searchNews(search, 1);
});

/* 函数定义 */
function getNews(currentPage) {
	qust.request({
		url: `dynamicState/select/page/${currentPage}/10`,
		method: "GET",
	}).then((res) => {
		if (res.code == 11000) {
			return false;
		}
		window.currentPage = res.data.data.current;
		window.maxPage = res.data.data.pages;
		$("#news-controller-state").setText(`${res.data.data.current}/${res.data.data.pages}`);

		window.mode = "get";
		let news = res.data.data.records;
		let newCardsTemplate = ``;
		for (let key in news) {
			let curNew = news[key];
			let commentTemplate = ``;
			qust.request({
				url: `getReplyById`,
				data: {
					dynamicId: curNew.id,
				},
			}).then((res) => {
				if (res.data.data != undefined) {
					let comment = [];
					res.data.data.forEach((item, index) => {
						if (item.replyId == 0) {
							comment.push(item);
						}
					});
					if (comment.length != 0) {
						commentTemplate += `<div class="comment-area">`;
						for (let key in comment) {
							let reply = [];
							res.data.data.forEach((item, index) => {
								if (item.replyId == comment[key].id) {
									reply.push(item);
								}
							});
							let replyTemplate = "";
							if (reply.length != 0) {
								replyTemplate += `<div class="reply-area">`;
								for (let k in reply) {
									replyTemplate += `<div class="container">
									<img class="user-avatar" src="http://www.rushmc.top/${reply[k].replyerPhoto}" />
									<p>${reply[k].replyerName} 回复</p>
									<img class="user-avatar" src="http://www.rushmc.top/${reply[k].beReplyerPhoto}" />
									<p>${reply[k].beReplyerName}：</p>
									<div>${reply[k].commentsContent}</div>
									<div class="comment-button" style="right:60px" onclick="window.reply(${reply[k].dynamicStateId},${comment[key].id},${localStorage.getItem("uid")},${reply[k].replyerId})">回复</div>
									<div class="comment-button" onclick="window.delComment(${reply[k].id})">删除</div>
									</div>`;
								}
								replyTemplate += `</div>`;
							}

							commentTemplate += `<div class="comment">
							<div class="container"><img class="user-avatar" src="http://www.rushmc.top/${comment[key].replyerPhoto}" />
							<p>${comment[key].replyerName} 评论</p> <img class="user-avatar" src="http://www.rushmc.top/${comment[key].beReplyerPhoto}" /><p>${comment[key].beReplyerName}：</p>
							<div>${comment[key].commentsContent}</div>
							<div class="comment-button" style="right:60px" onclick="window.reply(${comment[key].dynamicStateId},${comment[key].id},${localStorage.getItem("uid")},${comment[key].replyerId})">回复</div>
							<div class="comment-button" onclick="window.delComment(${comment[key].id})">删除</div>
							</div>
							${replyTemplate}
							</div>`;
						}
						commentTemplate += `</div>`;
					}
				}

				// 处理配图
				let picsTemplate = ``;
				curNew.urls.forEach((item) => {
					picsTemplate += `<img src="http://www.rushmc.top/${item}" />`;
				});

				newCardsTemplate += `<div class="new-card">
            <div class="new-title" id="new-title">
                <a class="author" style="font-weight:500;font-size:16px" href="/html/user_center.html?uid=${curNew.userId}&uname=${curNew.username}">${
					curNew.username
				}</a><p>  在${curNew.creationTime.substr(0, 10)}说</p>
                <div>${curNew.title}</div>
            </div>
            <div class="content">${curNew.content}</div>
            <div class="pics">
                ${picsTemplate}
            </div>
			<div class="field comment">
				<input type="text" id="comment${curNew.id}" class="search comment" placeholder="添加评论" /><i class="far fa-paper-plane search-icon" id="search-button" onclick="window.addComment(${
					curNew.id
				},${localStorage.getItem("uid")},${curNew.userId})"></i>
			</div>
				${commentTemplate}
        </div>`;

				$("#news").setHtml(newCardsTemplate);
			});
		}
	});
}

function searchNews(key, current) {
	qust.request({
		url: `dynamicState/search/${key}/page/${current}/10`,
		method: "GET",
	}).then((res) => {
		if (res.data.code == 11000) {
			$("#search").setValue("");
			$$.showModal({
				title: "搜索失败",
				content: "找不到符合条件的动态",
			}).then(() => {
				getNews(1);
			});

			return false;
		} else {
			$$.showModal({
				title: "搜索成功",
				content: "赞👍",
			});
		}

		window.mode = "search";
		window.currentPage = res.data.data.current;
		window.maxPage = res.data.data.pages;
		$("#news-controller-state").setText(`${res.data.data.current}/${res.data.data.pages}`);

		let news = res.data.data.records;
		let newCardsTemplate = ``;
		for (let key in news) {
			let curNew = news[key];
			let commentTemplate = ``;
			qust.request({
				url: `getReplyById`,
				data: {
					dynamicId: curNew.id,
				},
			}).then((res) => {
				if (res.data.data != undefined) {
					let comment = [];
					res.data.data.forEach((item, index) => {
						if (item.replyId == 0) {
							comment.push(item);
						}
					});
					if (comment.length != 0) {
						commentTemplate += `<div class="comment-area">`;
						for (let key in comment) {
							let reply = [];
							res.data.data.forEach((item, index) => {
								if (item.replyId == comment[key].id) {
									reply.push(item);
								}
							});
							let replyTemplate = "";
							if (reply.length != 0) {
								replyTemplate += `<div class="reply-area">`;
								for (let k in reply) {
									replyTemplate += `<div class="container">
									<img class="user-avatar" src="http://www.rushmc.top/${reply[k].replyerPhoto}" />
									<p>${reply[k].replyerName} 回复</p>
									<img class="user-avatar" src="http://www.rushmc.top/${reply[k].beReplyerPhoto}" />
									<p>${reply[k].beReplyerName}：</p>
									<div>${reply[k].commentsContent}</div>
									<div class="comment-button" style="right:60px" onclick="window.reply(${reply[k].dynamicStateId},${comment[key].id},${localStorage.getItem("uid")},${reply[k].replyerId})">回复</div>
									<div class="comment-button" onclick="window.delComment(${reply[k].id})">删除</div>
									</div>`;
								}
								replyTemplate += `</div>`;
							}

							commentTemplate += `<div class="comment">
							<div class="container"><img class="user-avatar" src="http://www.rushmc.top/${comment[key].replyerPhoto}" />
							<p>${comment[key].replyerName} 评论</p> <img class="user-avatar" src="http://www.rushmc.top/${comment[key].beReplyerPhoto}" /><p>${comment[key].beReplyerName}：</p>
							<div>${comment[key].commentsContent}</div>
							<div class="comment-button" style="right:60px" onclick="window.reply(${comment[key].dynamicStateId},${comment[key].id},${localStorage.getItem("uid")},${comment[key].replyerId})">回复</div>
							<div class="comment-button" onclick="window.delComment(${comment[key].id})">删除</div>
							</div>
							${replyTemplate}
							</div>`;
						}
						commentTemplate += `</div>`;
					}
				}

				// 处理配图
				let picsTemplate = ``;
				curNew.urls.forEach((item) => {
					picsTemplate += `<img src="http://www.rushmc.top/${item}" />`;
				});

				newCardsTemplate += `<div class="new-card">
            <div class="new-title" id="new-title">
                <a href="x" class="author">${curNew.username}</a><p>在${curNew.creationTime.substr(0, 10)}说</p>
                <div>${curNew.title}</div>
            </div>
            <div class="content">${curNew.content}</div>
            <div class="pics">
                ${picsTemplate}
            </div>
			<div class="field comment">
				<input type="text" id="comment${curNew.id}" class="search comment" placeholder="添加评论" /><i class="far fa-paper-plane search-icon" id="search-button" onclick="window.addComment(${
					curNew.id
				},${localStorage.getItem("uid")},${curNew.userId})"></i>
			</div>
				${commentTemplate}
        </div>`;

				$("#news").setHtml(newCardsTemplate);
			});
		}
	});
}

window.addComment = (dynamicStateId, replyerId, beReplyerId) => {
	let content = $(`#comment${dynamicStateId}`).value;
	if (content.length == 0) {
		$$.showModal({
			title: "评论失败",
			content: "请输入内容",
		});
		return false;
	}
	qust.request({
		url: "comment/insert",
		data: {
			dynamicStateId,
			replyerId,
			beReplyerId,
			commentsContent: content,
		},
	}).then((res) => {
		$(`#comment${dynamicStateId}`).setValue("");
		$$.showModal({
			title: "评论成功",
			content: `${res.data.msg}`,
		}).then(() => {
			location.reload();
		});
	});
};

window.reply = (dynamicStateId, replyId, replyerId, beReplyerId) => {
	let content = prompt("请输入回复内容");
	if (content == "") {
		$$.showModal({
			title: "回复失败",
			content: "请输入内容",
		});
		return false;
	}
	qust.request({
		url: "comment/reply",
		data: {
			dynamicStateId,
			replyId,
			replyerId,
			beReplyerId,
			commentsContent: content,
		},
	}).then((res) => {
		$$.showModal({
			title: "回复成功",
			content: `${res.data.msg}`,
		}).then(() => {
			location.reload();
		});
	});
};

window.delComment = (id) => {
	let r = confirm("确定删除吗?");
	if (r) {
		qust.request({
			url: "comment/delete",
			data: {
				id,
			},
		}).then((res) => {
			$$.showModal({
				title: "删除成功",
				content: `${res.data.msg}`,
			}).then(() => {
				location.reload();
			});
		});
	}
};
